package dao

import (
	"douyin/model"
	"sync"

	"gorm.io/gorm"
)

type userDAO struct{}

var (
	userDAOInstance *userDAO
	userDAOOnce     sync.Once
)

// NewUser 单例模式创建 userLoginDAO 实例
func NewUser() *userDAO {
	userDAOOnce.Do(func() {
		userLoginInstance = &userLoginDAO{}
	})

	return userDAOInstance
}

// Create 根据 values 里面的参数 （k-v） 创建 User 实体
func (*userDAO) Create(values map[string]interface{}) error {
	//TODO 增
	err := db.Model(&model.User{}).Create(values).Error
	if err != nil {
		return err
	}

	return nil
}

func (*userDAO) Delete() {
	//TODO 删
}

func (*userDAO) Update() {
	//TODO 改
}

func (*userDAO) Query(conditions map[string]interface{}) (*model.User, error) {
	var u model.User
	err := db.Model(&model.User{}).
		Select([]string{"user_id", "follow_count", "follower_count"}).
		Where(conditions).
		First(&u).Error

	if err != nil {
		return nil, err
	}

	return &u, nil
}

// IncreaseFollowCount 增加对应用户的关注数量
func (*userDAO) IncreaseFollowCount(id int64, count int64) error {
	return db.Model(model.User{}).Where("user_id = ?", id).Update("follow_count", gorm.Expr("follow_count + ?", count)).Error
}

// DecreaseFollowCount 增加对应用户的关注数量
func (*userDAO) DecreaseFollowCount(id int64, count int64) error {
	return db.Model(model.User{}).Where("user_id = ?", id).Update("follow_count", gorm.Expr("follow_count - ?", count)).Error
}

// IncreaseFollowerCount 增加对应用户的关注数量
func (*userDAO) IncreaseFollowerCount(id int64, count int64) error {
	return db.Model(model.User{}).Where("user_id = ?", id).Update("follower_count", gorm.Expr("follower_count + ?", count)).Error
}

// DecreaseFollowerCount 增加对应用户的关注数量
func (*userDAO) DecreaseFollowerCount(id int64, count int64) error {
	return db.Model(model.User{}).Where("user_id = ?", id).Update("follower_count", gorm.Expr("follower_count - ?", count)).Error
}
